package com.pangu.web.captcha;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.Ioc;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.pangu.core.AppConstants;
import com.pangu.util.BaseUtil;
import com.pangu.util.CookieUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class ImageCaptchaServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 3191367338327924272L;

	protected ImageCaptchaService captchaService;

	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		
		ServletContext context = servletConfig.getServletContext();
		Ioc ioc = (Ioc) context.getAttribute(Ioc.class.getName());
		captchaService = (ImageCaptchaService) ioc.get(ImageCaptchaService.class, "imageCaptchaService");
	}

	protected void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws ServletException, IOException {

		byte[] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		String captchaId = BaseUtil.randomUniqueString();
		try {
			BufferedImage challenge = captchaService.getImageChallengeForID(captchaId,
					httpServletRequest.getLocale());

			// a jpeg encoder
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(challenge);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		} catch (CaptchaServiceException e) {
			e.printStackTrace();
			httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}

		CookieUtil.setCookie(httpServletResponse, AppConstants.CAPTCHA_COOKIENAME, captchaId);
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

		// flush it in the response
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}
}
